<?php
/**
 * @link https://ym2.cleverstone.top
 * @copyright Copyright (c) 2020 Yii Manager Software LLC
 */

namespace common\handlers\backend;

use Yii;
use common\handlers\BaseHandler;
use common\helper\App;
use common\models\Admin;
use yii\web\Response;

/**
 * 检查管理员状态
 * @author cleverstone
 * @since ym2.0
 */
class BeforeActionValidateUserState extends BaseHandler
{
    /**
     * @param \yii\base\ActionEvent $event
     */
    public function run($event)
    {
        $user = $this->user;
        if (!$user->isGuest) {
            /** @var Admin $identity */
            $identity = $user->identity;
            // 拥有者不检查
            if ($identity->group == Admin::ADMIN_GROUP) {
                return;
            }

            // 封停
            if ($identity->status == Admin::STATUS_INACTIVE) {
                $user->logout();

                $denyTime = $identity->deny_end_time ? strtotime($identity->deny_end_time) : null;
                $duration = Yii::$app->formatter->asRelativeTime($denyTime);
                $flashError = $denyTime ? "您的账号【{$identity->username}】已被锁定, 请{$duration}重试" : "您的账号【{$identity->username}】已被永久冻结";

                $response = $this->response;
                if ($this->request->isAjax) {
                    $response->format = Response::FORMAT_JSON;
                    $response->data = [
                        'code' => App::params('http.res.failure'),
                        'msg' => $flashError,
                    ];
                } else {
                    $response->redirect([App::params('admin.route.login')]);
                }

                $this->session->setFlash(App::params('admin.session.flash.error'), $flashError);

                $event->isValid = false;
                $event->handled = true;
            }
        }
    }
}